/**
 * @class Spark.MenuButton
 * @extends Spark.Button
 * <p>菜单按钮组件.
 * @author njq.niu@hand-china.com
 * @constructor
 * @param {Object} config 配置对象. 
 */
$S.MenuButton = Ext.extend($S.Button,{
    downCss:'s-btn-down',
    align:"r",
    initComponent : function(config){
        $S.MenuButton.superclass.initComponent.call(this,config);
        this.menuId = config.id+'_menu';
        this.align = config.align||this.align;
    },
    initEvents : function(){
        $S.MenuButton.superclass.initEvents.call(this);
        this.addEvents(
        /**
         * @event down
         * down事件.
         * @param {Spark.MenuButton} button 按钮对象.
         */
        'down',
        /**
         * @event up
         * up事件.
         * @param {Spark.MenuButton} button 按钮对象.
         */
        'up');
    },
    processListener: function(ou){
        $S.MenuButton.superclass.processListener.call(this, ou);
        var menu = $(this.menuId);
        if(menu){
            menu[ou]("click", this.onMenuClick,  this);
        }
    },
    onMenuClick: function(){
        this.up();
    },
    onMouseDown: function(e){
        e.preventDefault();
        this.focus();
        if(!this.disabled){
            this.wrap.hasClass(this.downCss) ? this.up() : this.down();
        }
    },
    onDocumentMouseDown: function(e){
        if(this.wrap.contains(e.target) || ($(this.menuId) && $(this.menuId).isEventFromComponent(e.target))) return;
        this.up();
    },
    showMenu: function(){
        var menu = $(this.menuId);
        if(menu){
            menu.wrap.setDisplayed('block');
            var vs = (Ext.isIE6 || Ext.isIE7) ? 2 : 0, xy = this.wrap.getXY(),
            sl = document[Ext.isStrict&&!Ext.isWebKit?'documentElement':'body'].scrollLeft,
            st = document[Ext.isStrict&&!Ext.isWebKit?'documentElement':'body'].scrollTop,
            _x = xy[0] - sl,_y = xy[1] - st,
            W=menu.wrap.getWidth(),H=menu.wrap.getHeight(),
            PH=this.wrap.getHeight(),PW=this.wrap.getWidth(),
            BH=$S.getViewportHeight()-3,BW=$S.getViewportWidth()-3,
            x = this.align == 'r' ? ((_x+W)>BW ? (_x+PW-W):_x) : ((_x+PW-W)>0 ? (_x+PW-W) : _x),
            y = (_y+PH+H)>BH ? (_y-H) : (_y+PH);
            menu.show(x+sl-vs,y+st-vs);
        }
    },
    hideMenu: function(){
        var menu = $(this.menuId);
        if(menu){            
            menu.hide();
        }
    },
    down: function(){
        this.wrap.addClass(this.downCss);
        Ext.get(document.documentElement).on("mousedown", this.onDocumentMouseDown, this);
        this.showMenu();
        this.fireEvent("down", this);
    },
    up:function(){
        this.wrap.removeClass(this.downCss);
        Ext.get(document.documentElement).un("mousedown", this.onDocumentMouseDown, this);
        this.hideMenu();
        this.fireEvent("up", this);
    }
})